package com.xmotor.test_sign.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpConnectionPoolUtil {


    private static final int CONNECT_TIMEOUT = 3 * 1000;	//设置连接建立的超时时间为3s
    private static final int SOCKET_TIMEOUT = 20 * 1000;	//设置等待数据超时时间20s
    private static final int MAX_CONN = 500; // 最大连接数
    private static final int Max_PRE_ROUTE = 200;	//默认每路由最高200并发
    //private static final int MAX_ROUTE = 500;	//最大路由并发
    private static final int HTTP_IDEL_TIMEOUT = 60 * 1000;	//30s空闲链接
    private static final int HTTP_MONITOR_INTERVAL = 60 * 1000;	//定时关闭连接池时间间隔
    private static final String CHARSET = "UTF-8";	//字符集
    
    private static CloseableHttpClient httpClient; // 发送请求的客户端单例
    private static PoolingHttpClientConnectionManager manager; //连接池管理类
    private static ScheduledExecutorService monitorExecutor;

    private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全

    /**
     * 对http请求进行基本设置
     * @param httpRequestBase http请求
     */
    private static void setRequestConfig(HttpRequestBase httpRequestBase){
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();

        httpRequestBase.setConfig(requestConfig);
    }
    
    /**
     * 描述：获取httpClient对象
     * @return
     */
    public static CloseableHttpClient getHttpClient(){
        /*String hostName = url.split("/")[2];
        //System.out.println(hostName);
        int port = 80;
        if (hostName.contains(":")){
            String[] args = hostName.split(":");
            hostName = args[0];
            port = Integer.parseInt(args[1]);
        }*/

        if (httpClient == null){
            //多线程下多个线程同时调用getHttpClient容易导致重复创建httpClient对象的问题,所以加上了同步锁
            synchronized (syncLock){
                if (httpClient == null){
                    httpClient = createHttpClient();
                    //开启监控线程,对异常和空闲线程进行关闭
                    monitorExecutor = Executors.newScheduledThreadPool(1);
                    monitorExecutor.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            //关闭异常连接
                            manager.closeExpiredConnections();
                            //关闭30s空闲的连接
                            manager.closeIdleConnections(HTTP_IDEL_TIMEOUT, TimeUnit.MILLISECONDS);
                            //log.info("close expired and idle for over 30s connection");
                        }
                    }, HTTP_MONITOR_INTERVAL, HTTP_MONITOR_INTERVAL, TimeUnit.MILLISECONDS);
                }
            }
        }
        
        return httpClient;
    }

    /**
     * 根据host和port构建httpclient实例
     * @return
     */
    public static CloseableHttpClient createHttpClient(){
        ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", plainSocketFactory)
                .register("https", sslSocketFactory).build();

        manager = new PoolingHttpClientConnectionManager(registry);
        //设置连接参数
        manager.setMaxTotal(MAX_CONN); // 最大连接数
        manager.setDefaultMaxPerRoute(Max_PRE_ROUTE); // 路由最大连接数

        //HttpHost httpHost = new HttpHost(host, port);
        //manager.setMaxPerRoute(new HttpRoute(httpHost), MAX_ROUTE);

        //请求失败时,进行请求重试
        /*HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i > 3){
                    //重试超过3次,放弃请求
                    log.error("retry has more than 3 time, give up request");
                    return false;
                }
                if (e instanceof NoHttpResponseException){
                    //服务器没有响应,可能是服务器断开了连接,应该重试
                    log.error("receive no response from server, retry");
                    return true;
                }
                if (e instanceof SSLHandshakeException){
                    // SSL握手异常
                    log.error("SSL hand shake exception");
                    return false;
                }
                if (e instanceof InterruptedIOException){
                    //超时
                    log.error("InterruptedIOException");
                    return false;
                }
                if (e instanceof UnknownHostException){
                    // 服务器不可达
                    log.error("server host unknown");
                    return false;
                }
                if (e instanceof ConnectTimeoutException){
                    // 连接超时
                    log.error("Connection Time out");
                    return false;
                }
                if (e instanceof SSLException){
                    log.error("SSLException");
                    return false;
                }

                HttpClientContext context = HttpClientContext.adapt(httpContext);
                HttpRequest request = context.getRequest();
                if (!(request instanceof HttpEntityEnclosingRequest)){
                    //如果请求不是关闭连接的请求
                    return true;
                }
                return false;
            }
        };

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).setRetryHandler(handler).build();*/
        
        CloseableHttpClient client = HttpClients.custom()
        		.setConnectionManager(manager)
        		.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
        		.build();	//关闭重试机制
        
        return client;
    }

    /**
     * 设置post请求的参数
     * @param httpPost
     * @param params
     */
    private static void setPostParams(HttpPost httpPost, Map<String, Object> params){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keys = params.keySet();
        for (String key: keys){
        	String value = params.get(key) != null ? params.get(key).toString() : "";
            nvps.add(new BasicNameValuePair(key, value));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, CHARSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 描述：设置header
     * @param headers
     */
    private static void setHeaders(HttpRequestBase request,Map<String, String> headers){
    	Set<String> keys = headers.keySet();  
        for(Iterator<String> i=keys.iterator(); i.hasNext();){  
            String key = (String) i.next();  
            request.setHeader(key, headers.get(key));  
        }
    }
    
    /**
     * 描述：post请求
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, Object> params){
    	return post(url,params,null);
    }

    /**
     * Post请求
     * @param url
     * @param jsonString
     * @return
     */
    public static String post(String url,String jsonString){

        try{
            // 定义HttpClient
            CloseableHttpClient client = getHttpClient();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setConnectTimeout(20000)
                    .setSocketTimeout(600000)
                    .build();

            StringEntity entity = new StringEntity(
                    jsonString,
                    ContentType.create("application/json", Consts.UTF_8));

            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(entity);
            httppost.setConfig(requestConfig);

            CloseableHttpResponse httpResponse = client.execute(httppost);

            HttpEntity responseEntity = httpResponse.getEntity();
            String resData = responseEntity != null ? EntityUtils.toString(responseEntity) : null;

            return resData;
        }
        catch(Exception e){
            log.error("Exception", e);
            return null;
        }
    }


    /**
     * Post请求
     * @param url
     * @param jsonString
     * @return
     */
        public static String post(String url,String jsonString,Map<String,String> headers){

        try{
            // 定义HttpClient
            CloseableHttpClient client = getHttpClient();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setConnectTimeout(20000)
                    .setSocketTimeout(600000)
                    .build();

            StringEntity entity = new StringEntity(
                    jsonString,
                    ContentType.create("application/json", Consts.UTF_8));

            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(entity);
            httppost.setConfig(requestConfig);
            setHeaders(httppost,headers);
            CloseableHttpResponse httpResponse = client.execute(httppost);

            HttpEntity responseEntity = httpResponse.getEntity();
            String resData = responseEntity != null ? EntityUtils.toString(responseEntity) : null;

            return resData;
        }
        catch(Exception e){
            log.error("Exception", e);
            return null;
        }
    }
    /**
     * 描述：post请求
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static String post(String url, Map<String, Object> params,Map<String, String> headers){
        HttpPost httpPost = new HttpPost(url);
        setRequestConfig(httpPost);
        setPostParams(httpPost, params);
        if(headers != null){
        	setHeaders(httpPost,headers);
        }
        CloseableHttpResponse response = null;
        InputStream in = null;
        String result = null;
        try {
            response = getHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(response.getEntity(),CHARSET);
            }else{
                log.error("entity为null！请求url："+url+"，入参："+params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (null != in) in.close();
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }
    
    /**
     * 描述：Post请求
     * 仅提供ICBC调用
     * @param url
     * @param postEntity
     * @return
     */
    public static byte[] icbcPost(String url, HttpEntity postEntity){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(postEntity);
        setRequestConfig(httpPost);
        CloseableHttpResponse response = null;
        InputStream in = null;
        byte[] result = null;
        try {
            response = getHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
            	result = IOUtils.toByteArray(entity.getContent());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (null != in) in.close();
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }

    /**
     * 描述：get请求
     * @param url
     * @return
     */
    public static String doGet(URI url){
    	return doGet(url,null);
    }
    
    /**
     * 描述：get请求
     * @param url
     * @param headers
     * @return
     */
    public static String doGet(URI url,Map<String, String> headers){
        //发送get请求
        HttpGet httpGet = new HttpGet(url);
        setRequestConfig(httpGet);
        if(headers != null){
        	setHeaders(httpGet,headers);
        }
        
        CloseableHttpResponse response = null;
        String result = null;
        try{
        	response = getHttpClient().execute(httpGet);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
            	HttpEntity entity = response.getEntity();
            	if (entity != null) {
            		result = EntityUtils.toString(response.getEntity(),CHARSET);
                }
            }
        }
        catch(Exception e){
        	e.printStackTrace();
        }
        finally {
            try{
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result;
	}

    /**
     * 关闭连接池
     */
    public static void closeConnectionPool(){
        try {
            httpClient.close();
            manager.close();
            monitorExecutor.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 微信开发 post
     * @param url       目标url
     * @param params    传参，json串
     * @param headers
     * @return
     * @throws IOException
     */
    public static String weixinPost(String url,String params, Map<String, String> headers){
        HttpPost httpPost = new HttpPost(url);
        setRequestConfig(httpPost);
        StringEntity se = new StringEntity(params,"UTF-8");
        httpPost.setEntity(se);
        if(headers != null){
            setHeaders(httpPost,headers);
        }
        CloseableHttpResponse response = null;
        InputStream in = null;
        String result = null;
        try {
            response = getHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(response.getEntity(),CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (null != in) in.close();
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 微信开发 post,返回字节
     * @param url       目标url
     * @param params    传参，json串
     * @param headers
     * @return
     * @throws IOException
     */
    public static byte[] weixinPostReturnByte(String url,String params, Map<String, String> headers){
        HttpPost httpPost = new HttpPost(url);
        setRequestConfig(httpPost);
        StringEntity se = new StringEntity(params,"UTF-8");
        httpPost.setEntity(se);
        if(headers != null){
            setHeaders(httpPost,headers);
        }
        CloseableHttpResponse response = null;
        InputStream in = null;
        byte[] result = null;
        try {
            response = getHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toByteArray(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (in != null) in.close();
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
